<template>
    <div>
      <!-- 查询表单 -->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="">
          <el-input v-model="searchForm.name" placeholder="作业单状态" clearable />
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="searchForm.state" placeholder="出库单ID" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" round @click="search">查询</el-button>
        </el-form-item>
      </el-form>
  
      <!-- 导出按钮 -->
      <el-button type="warning" round @click="handleExport">导出数据</el-button>
      <div style="height: 20px;"></div>
  
      <!-- 数据展示区域 -->
      <el-table :data="tableData.resultList" border style="width: 100%" max-height="500">
        <el-table-column prop="outId" sortable label="出库订单序号">
          <template #default="scope">
            <span :class="{ 'unassigned-text': !scope.row.outId }">
              {{ scope.row.outId || '未分配' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="exeWorkerName" sortable label="执行人">
          <template #default="scope">
            <span :class="{ 'unassigned-text': !scope.row.exeWorkerName }">
              {{ scope.row.exeWorkerName || '未分配' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="loadName" sortable label="装卸点">
          <template #default="scope">
            <span :class="{ 'unassigned-text': !scope.row.loadName }">
              {{ scope.row.loadName || '未分配' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="exePlanTime" sortable label="计划时间">
          <template #default="scope">
            <span :class="{ 'unassigned-text': !scope.row.exePlanTime }">
              {{ scope.row.exePlanTime || '未分配' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="exeTime" sortable label="完成时间">
          <template #default="scope">
            <span :class="{ 'unassigned-text': !scope.row.exeTime }">
              {{ scope.row.exeTime || '未分配' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" sortable label="作业单状态">
          <template #default="scope">
            <el-tag
              :type="getStatusType(scope.row.status)"
              effect="plain"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
  
        <el-table-column prop="createTime" sortable label="创建时间" />
        <el-table-column prop="createName" sortable label="创建人" />
        <el-table-column prop="updateTime" sortable label="修改时间" />
        <el-table-column prop="updateName" sortable label="修改人" />
  
        <!-- 操作列 -->
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <template v-if="scope.row.status !== '2'">
              <el-button type="primary" size="small" style="margin-right: 5px;" @click="handleAssign(scope.row)">分配</el-button>
              <el-button type="success" size="small" style="margin-right: 5px;" @click="handleStart(scope.row)">开始作业</el-button>
              <el-button size="small" style="margin-right: 5px;" @click="handleComplete(scope.row)">完成作业</el-button>
            </template>
            <el-button type="info" size="small" @click="handleDelete(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分配对话框 -->
      <el-dialog v-model="assignDialogVisible" title="分配出库作业" width="600">
        <el-form :model="assignForm">
          <el-form-item label="计划执行时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="assignForm.exePlanTime"
              type="datetime"
              placeholder="选择计划执行时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="执行时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="assignForm.exeTime"
              type="datetime"
              placeholder="选择执行时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="执行人" :label-width="formLabelWidth">
            <el-select v-model="assignForm.exeWorkerName" placeholder="请选择执行人" style="width: 100%">
              <el-option
                v-for="item in employeeOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="装卸点" :label-width="formLabelWidth">
            <el-select v-model="assignForm.loadName" placeholder="请选择装卸点" style="width: 100%">
              <el-option
                v-for="item in loadPointOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          
          <!-- 商品列表 -->
          <el-form-item label="商品信息" :label-width="formLabelWidth">
            <div v-for="(item, index) in assignForm.goodsList" :key="index">
              <el-row :gutter="10" style="margin-bottom: 10px;">
                <el-col :span="7">
                  <el-input v-model="item.goodsName" placeholder="商品名称" />
                </el-col>
                <el-col :span="7">
                  <el-input v-model="item.goodsCount" placeholder="数量" type="number" />
                </el-col>
                <el-col :span="7">
                  <!-- <el-select v-model="item.shelfName" placeholder="请选择货架号" style="width: 100%">
                    <el-option
                      v-for="shelf in shelfOptions"
                      :key="shelf"
                      :label="shelf"
                      :value="shelf"
                    />
                  </el-select> -->
                </el-col>
                <el-col :span="3">
                  <el-button type="danger" @click="removeGoodsItem(index)">删除</el-button>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" @click="addGoodsItem">添加商品</el-button>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="assignDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAssignConfirm">确认</el-button>
          </div>
        </template>
      </el-dialog>
  
      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="出库作业单详情" width="800">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="出库订单序号">{{ detailData.outId }}</el-descriptions-item>
            <el-descriptions-item label="执行人">{{ detailData.exeWorkerName }}</el-descriptions-item>
            <el-descriptions-item label="装卸点">{{ detailData.loadName }}</el-descriptions-item>
            <el-descriptions-item label="计划时间">{{ detailData.exePlanTime }}</el-descriptions-item>
            <el-descriptions-item label="完成时间">{{ detailData.exeTime }}</el-descriptions-item>
            <el-descriptions-item label="作业单状态">{{ detailData.state === '1' ? '启用' : '未开始' }}</el-descriptions-item>
          </el-descriptions>
        </div>
  
        <!-- 商品列表 -->
        <div class="detail-section">
          <h3>商品信息</h3>
          <el-table :data="goodsList" border style="width: 100%">
            <el-table-column prop="goodsName" label="商品名称" />
            <el-table-column prop="goodsCount" label="数量" />
            <el-table-column prop="shelfName" label="货架号" />
          </el-table>
        </div>
  
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
  
      <!-- 分页区域 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchCondition.pageNum"
          v-model:page-size="searchCondition.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.totalNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import {searchEmployeeName,searchShelfName,searchPositioName, searchOutStoreGoods, searchOutOperation,searchOutOperationGoods,updateOutOperation,updateOutOperationStatus } from '../api/api.js'
  
  // ==============================
  
  // 表格数据对象
  const tableData = ref(
   [], // 当前页数据列表
  )
  
  // 对话框显示状态
  const assignDialogVisible = ref(false) // 指派对话框
  const formLabelWidth = '120px'         // 表单标签宽度
  
  // 搜索表单数据
  const searchForm = reactive({
    outId: '',
    status: ''
  })
  
  // 指派表单数据
  const assignForm = reactive({
    id: '',
    exePlanTime: '',
    exeTime: '',
    exeWorkerName: '',
    loadName: '',
    outId: '',
    goodsList: []  // 添加商品列表
  })
  
  const searchCondition = {
    outId: '',
    status: '',
    pageNum: 1,      
    pageSize: 10     
  }
  
  // 详情对话框显示状态
  const detailDialogVisible = ref(false)
  
  // 详情数据
  const detailData = reactive({
    outId: '',
    exeWorkerName: '',
    loadName: '',
    exePlanTime: '',
    exeTime: '',
    state: ''
  })
  
  // 商品列表数据
  const goodsList = ref([])
  
  // 添加下拉选项数据
  const employeeOptions = ref([])
  const loadPointOptions = ref([])
  const shelfOptions = ref([])
  
  // 获取下拉选项数据的方法
  const fetchSelectOptions = async () => {
    try {
      // 获取执行人选项
      const empRes = await searchEmployeeName()
      employeeOptions.value = empRes.data.data || []
  
      // 获取装卸点选项
      const posRes = await searchPositioName()
      loadPointOptions.value = posRes.data.data || []
  
      // 获取货架选项
      const shelfRes = await searchShelfName()
      shelfOptions.value = (shelfRes.data.data || [])
        .filter(item => item.type === '2')
        .map(item => item.shelfName)
    } catch (error) {
      ElMessage.error('获取选项数据失败')
    }
  }
  
  // ==============================
  
  /**
   * 查询列表
   */
  const search = async () => {
    searchCondition.outId = searchForm.outId
    searchCondition.status = searchForm.status
  
    const res = await searchOutOperation(searchCondition)
    if (res.data.code == 200) {
      tableData.value = res.data.data
      ElMessage.success('查询成功')
      return
    }else {
      ElMessage.error('查询失败')
    }
    console.log(tableData.value)
  
  }
  
  /**
   * 分配按钮点击事件
   */
  const handleAssign = async (row) => {
    try {
      // 获取所有下拉选项数据
      await fetchSelectOptions()
      
      // 获取商品列表数据
      const res = await searchOutStoreGoods(row.outId)
      goodsList.value = res.data.data
      console.log(goodsList.value)
      
      
      // 设置表单数据
      assignForm.id = row.id
      assignForm.exePlanTime = row.exePlanTime
      assignForm.exeTime = row.exeTime
      assignForm.exeWorkerName = row.exeWorkerName
      assignForm.loadName = row.loadName
      assignForm.outId = row.outId
      
      // 如果有商品数据则使用已有数据，否则创建空商品项
      assignForm.goodsList = goodsList.value || [{
      goodsName: '',
      goodsCount: 1,
      shelfName: ''
      }]
      
      assignDialogVisible.value = true
    } catch (error) {
      ElMessage.error('获取商品数据失败')
    }
  }
  
  /**
   * 分配确认事件
   */
  const handleAssignConfirm = async () => {
    try {
      await updateOutOperation(assignForm)
      ElMessage.success('分配成功')
      search() // 刷新列表
      assignDialogVisible.value = false
    } catch (error) {
      ElMessage.error('分配失败')
    }
  }
  
  /**
   * 删除
   */
  const handleDelete = async (row) => {
    // 保存基本信息
    Object.assign(detailData, row)
    console.log(detailData)
    
    try {
      // 获取商品列表
      const res = await searchOutOperationGoods(row.id)
      goodsList.value = res.data.data
      // 显示详情对话框
      detailDialogVisible.value = true
    } catch (error) {
      ElMessage.error('获取详情失败')
    }
  }
  
  /**
   * 改变每页显示数量
   */
  const handleSizeChange = (val) => {
    
    search()
  }
  
  /**
   * 改变当前页码
   */
  const handleCurrentChange = (val) => {
  
    search()
  }
  
  //更新状态
  const toggleStatus = (row) => {
    row.state = row.state === '1' ? '0' : '1'
    updatePosition(row).then(() => {
      search()
    })
  }
  
  /**
   * 导出数据
   */
  const handleExport = () => {
    // 导出逻辑
  }
  
  /**
   * 添加商品项
   */
  const addGoodsItem = () => {
    assignForm.goodsList.push({
      goodsName: '',
      goodsCount: 1,
      shelfName: ''
    })
  }
  
  /**
   * 删除商品项
   */
  const removeGoodsItem = (index) => {
    assignForm.goodsList.splice(index, 1)
  }
  
  /**
   * 获取状态文本
   */
  const getStatusText = (status) => {
    switch (status) {
      case '0':
        return '未开始'
      case '1':
        return '执行中'
      case '2':
        return '已完成'
      default:
        return '未知状态'
    }
  }
  
  /**
   * 获取状态标签类型
   */
  const getStatusType = (status) => {
    switch (status) {
      case '0':
        return 'info'     // 未开始 - 灰色
      case '1':
        return 'primary'  // 执行中 - 蓝色
      case '2':
        return 'success'  // 已完成 - 绿色
      default:
        return ''
    }
  }
  
  /**
   * 开始作业
   */
  const handleStart = async (row) => {
    try {
      await updateOutOperationStatus({
        outId: row.outId,
        status: '1'  // 设置状态为执行中
      })
      // 只更新当前行的状态
      row.status = '1'
      ElMessage.success('开始作业成功')
    } catch (error) {
      ElMessage.error('开始作业失败')
    }
  }
  
  /**
   * 完成作业
   */
  const handleComplete = async (row) => {
    try {
      await updateOutOperationStatus({
        outId: row.outId,
        status: '2'  // 设置状态为已完成
      })
      // 只更新当前行的状态
      row.status = '2'
      search() // 刷新列表
      // ElMessage.success('完成作业成功') 
    } catch (error) {
      ElMessage.error('完成作业失败')
    }
  }
  
  onMounted(() => {
    search()
  })
  </script>
  
  <style scoped>
   .demo-form-inline .el-input {
    --el-input-width: 220px;
  }
  
  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }
  
  .operation-area {
    margin: 15px 0;
  }
  
  .pagination-area {
    margin-top: 20px;
    text-align: right;
  }
  
  .unassigned-text {
    color: #909399;
    opacity: 0.7;
  }
  
  .el-row {
    margin-bottom: 10px;
  }
  
  .detail-section {
    margin-bottom: 20px;
  }
  
  .detail-section h3 {
    margin-bottom: 15px;
    font-weight: bold;
  }
  </style>
